import path from "node:path";
import os from "node:os";
import type { ShareFileInfo } from "@common/lan-share-types.ts";
import fs from "node:fs";
import fsp from "node:fs/promises";

export const fileShareService = (() => {
  const dataDir = path.join(os.homedir(), ".devilbox/lan-share");
  const sharedDataFile = path.join(dataDir, "sharedFiles.json");

  const fileList: ShareFileInfo[] = [];

  async function ensureDataDir() {
    if (!fs.existsSync(dataDir)) {
      await fsp.mkdir(dataDir, { recursive: true });
    }
  }

  /**
   * 加载已分享的文件
   */
  async function loadSharedFiles() {
    fileList.length = 0;
    if (!fs.existsSync(sharedDataFile)) {
      return;
    }

    try {
      const content = await fsp.readFile(sharedDataFile, { encoding: "utf-8" });
      const list = JSON.parse(content);
      fileList.push(...list);
    } catch (e) {
      console.error(`[file-share-service] load shared files error`, e);
    }
  }

  async function saveFileList() {
    try {
      await ensureDataDir();
      await fsp.writeFile(sharedDataFile, JSON.stringify(fileList), { encoding: "utf-8" });
    } catch (e) {
      console.error(`[file-share-service] save file list error`, e);
    }
  }

  /**
   * 获取已分享的文件列表
   */
  const getSharedFileList = async () => {
    if (fileList.length === 0) {
      await loadSharedFiles();
    }
    return fileList;
  };

  /**
   * 新增文件分享
   * @param file
   */
  const addShareFile = (file: ShareFileInfo) => {
    const existsFile = fileList.find(it => it.path === file.path);
    if (!existsFile) {
      fileList.unshift(file);
      saveFileList().catch(() => void 0);
      return true;
    }
    return false;
  };

  /**
   * 删除文件分享
   * @param id
   */
  const deleteShareFile = (id: string) => {
    const idx = fileList.findIndex(it => it.id === id);
    if (idx !== -1) {
      fileList.splice(idx, 1);
      saveFileList().catch(() => void 0);
      return true;
    }
    return false;
  };

  return {
    ensureDataDir,
    loadSharedFiles,
    getSharedFileList,
    addShareFile,
    deleteShareFile,
  };
})();
